package com.wanmait.community.controller;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wanmait.community.util.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class CommonControllerAdvice {
    @Value("${spring.servlet.multipart.max-file-size}")//注入单个文件上传大小的值
    private String maxFileSize;
    //服务器端校验抛出的错误
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleValidException(MethodArgumentNotValidException ex) {
        List<String> errors = ex.getFieldErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        return AjaxResult.error(10005,"请求参数校验失败", errors);
    }
    //登录失败抛出的错误
    @ExceptionHandler(value = JWTVerificationException.class)
    public AjaxResult handleJWTVerificationException(JWTVerificationException ex) {
        return AjaxResult.error(10001,ex.getMessage());
    }
    //在线编辑器上传图片异常处理
    @ExceptionHandler(value= MaxUploadSizeExceededException.class)
    public AjaxResult handleException(MaxUploadSizeExceededException exception) {
        return AjaxResult.error("上传文件大小超出，最大允许：" + maxFileSize);
    }

}
